# @Time : 2024/3/9 下午1:12
# @Author  : hxg
# @Desc : ==============================================
# Life is Short I Use Python!!!                      ===
# ======================================================
# @Project : reminder
# @FileName: views
# @Software: PyCharm
import hashlib
import requests
import json

from rest_framework.decorators import api_view
from django.http.response import HttpResponseRedirect
from django.http.response import HttpResponse
from django.conf import settings
from django.contrib.auth import authenticate, login, logout
from user.models import User


@api_view(["get"])
def index(request):
    return HttpResponseRedirect('/admin')


@api_view(["get"])
def validate_wx_domain(request):
    """
    验证微信域名
    :param request:
    :return:
    """
    try:
        data = request.GET
        if len(data) == 0:
            return "hello, this is handle view"
        signature = data.get('signature')
        timestamp = data.get('timestamp')
        nonce = data.get('nonce')
        echostr = data.get('echostr')
        token = "485d9d2bdfb811eeac0528cdc4bb7170"
        print(request.GET, request.data)
        list = [token, timestamp, nonce]
        list.sort()
        sha1 = hashlib.sha1()
        map(sha1.update, list)
        hashcode = sha1.hexdigest()
        print("handle/GET func: hashcode, signature: ", hashcode, signature)
        if hashcode == signature:
            return HttpResponse(echostr)
        else:
            return HttpResponse(echostr)
    except Exception as e:
        return HttpResponse(e)

    from cryptography.hazmat.primitives.ciphers.aead import AESGCM
    import base64
    key = "Your32Apiv3Key"

    key_bytes = str.encode(key)
    nonce_bytes = str.encode(nonce)
    ad_bytes = str.encode(associated_data)
    data = base64.b64decode(ciphertext)

    aesgcm = AESGCM(key_bytes)
    return aesgcm.decrypt(nonce_bytes, data, ad_bytes)


@api_view(["get"])
def redirect(request):
    if request.GET:
        code = request.GET.get('code', None)
        state = request.GET.get('state', None)
        if state == '7':
            # 首页
            return HttpResponseRedirect('/weixin/index')

        if code is None or state is None:
            return HttpResponse('请求错误!')
        access_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type=authorization_code'.format(
            appid=settings.WX_PAY_APPID, secret=settings.WEIXIN_APP_SECRET, code=code)
        result = requests.get(access_token_url)
        result_json = json.loads(result.text)
        openid = result_json.get('openid', None)
        if openid is None:
            return HttpResponse('获取OpenID失败!')
        emp = User.objects.filter(weixin_unique_id=openid)
        if emp:
            emp = emp[0]
            django_user = emp.django_user
            logout(request)
            login(request, django_user)
            if state == '2':
                # 录入单据
                return HttpResponseRedirect('/weixin/input_receipt')
            elif state == '3':
                # 审核
                return HttpResponseRedirect('/weixin/auditing_receipt')
            elif state == '4':
                # 帮助
                return HttpResponseRedirect('/weixin/help')
            elif state == '6':
                # 按人报表
                return HttpResponseRedirect('/weixin/report?typeid=1')
            elif state == '12':
                # 按车辆报表
                return HttpResponseRedirect('/weixin/report?typeid=2')
            elif state == '13':
                # 按搅拌站报表
                return HttpResponseRedirect('/weixin/report?typeid=3')
            elif state == '10':
                # 职员查询自己的单
                return HttpResponseRedirect('/weixin/my_receipt')
            elif state == '11':
                # 管理员查询单流水
                return HttpResponseRedirect('/weixin/all_receipt')
            else:
                return HttpResponseRedirect('/weixin/index')
        else:
            request.session['openid'] = openid
            if state == '1':
                # 验证用户
                return HttpResponseRedirect('/weixin/linkworker')
            else:
                return HttpResponseRedirect('/weixin/index')
    else:
        return HttpResponseRedirect('/weixin/index')
